package ace.cmp.spring.graphql.data.jdbc.querydsl.core.controller.converter.impl;

import ace.cmp.spring.graphql.data.jdbc.querydsl.core.controller.converter.PageInputToPageableConverter;
import ace.cmp.spring.graphql.data.jdbc.querydsl.core.controller.model.PageInput;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;

/**
 * @author caspar
 * @date 2023/9/14 10:10
 */
public class PageInputToPageableConverterImpl implements PageInputToPageableConverter {
  @Override
  public Pageable convert(PageInput pageInput) {
    Sort sort = Sort.unsorted();
    if (CollectionUtils.isNotEmpty(pageInput.getSorts())) {
      List<Sort.Order> orders =
          pageInput.getSorts().stream()
              .map(
                  sortInput -> {
                    Sort.Order order =
                        sortInput.getAsc()
                            ? Sort.Order.asc(sortInput.getName())
                            : Sort.Order.desc(sortInput.getName());
                    return order;
                  })
              .collect(Collectors.toList());
      Sort.by(orders);
    }
    PageRequest pageRequest = PageRequest.of(pageInput.getPage(), pageInput.getSize(), sort);

    return pageRequest;
  }
}
